//
//  EFAPjtPlaceSelVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/23.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAPjtPlaceSelVC.h"
#import "GlobalHeader.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MJRefresh.h>
#import "EFAPjtResultsTVC.h"
#import "UIColor+XDHex.h"
#import "UIImage+XDAdd.h"

@interface EFAPjtPlaceSelVC ()<UITableViewDelegate, UITableViewDataSource, MAMapViewDelegate, AMapSearchDelegate, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate, EFAPjtResultsTVCDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *bgScrollView;
@property (weak, nonatomic) IBOutlet UIView *backgroundView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgViewHeight;
@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UIImageView *centerImgView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *cancelBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *sendBarBtnItem;
@property (strong, nonatomic) UISearchController *searchController;

@property (strong, nonatomic) AMapSearchAPI *search;
@property (strong, nonatomic) NSMutableArray<AMapPOI *> *searchPoiArray;

@property (assign, nonatomic) NSInteger searchPage;     //!< 当前Page
@property (strong, nonatomic) NSIndexPath *selIndexPath;//!< 选中的IndexPath;
@property (assign, nonatomic) BOOL isMapRegionChangedFromTb;    //!< 标记界面的变化从TableView点击引起的
@property (assign, nonatomic) BOOL isLocated;           //!< 用来标记第一次进入界面时是否定位的标记
@property (copy,   nonatomic) NSString *currentAddress; ///< 当前位置的地址
@property (assign, nonatomic) CGFloat historyY;         ///< 记录scrollview滑动方向使用
@end

static NSString *const kReuseCellId = @"UITableViewCell";

@implementation EFAPjtPlaceSelVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    
//    //界面出现之后再开始调用用户定位
//    self.mapView.zoomLevel = 17;
//    self.mapView.showsUserLocation = YES;
//}

- (void)updateViewConstraints {
    [super updateViewConstraints];
    // 设置一个view的高度
    self.bgViewHeight.constant = CGRectGetHeight([UIScreen mainScreen].bounds);
}

- (void)initNavigationBar {
    self.navigationItem.title = @"位置";
    self.navigationItem.leftBarButtonItem = self.cancelBarBtnItem;
    self.navigationItem.rightBarButtonItem = self.sendBarBtnItem;
}

- (void)initSubViews {
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // UIScrollView
    self.bgScrollView.bounces = NO;
    self.bgScrollView.scrollEnabled = NO;
    
    // UISearchController
    self.definesPresentationContext = YES;
    [self.backgroundView addSubview:self.searchController.searchBar];
    
    // MAMapView
    self.mapView.delegate = self;
    self.mapView.zoomLevel = 17;
    // 打开地图显示当前的定位
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    // UITableView
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
//    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionHeaderHeight = 60.0;
//    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionFooterHeight = 22.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 下拉刷新
//    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UIScrollViewDelegate
/// 备注：这里是滚动方向判断的示例代码
/**
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        self.historyY = scrollView.contentOffset.y;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        if (scrollView.contentOffset.y < self.historyY) {
            NSLog(@"down");
        } else if (scrollView.contentOffset.y > self.historyY) {
            NSLog(@"up");
        }
    }
}
*/

/**
 备注：注意这里发现当scrollview里面嵌套的tableview滚动时，直接设置父parent的scrollview的contentOffset:Animate发现动画会延时
 所以这里只能暂时把animate置为NO，并且用UIView自带的动画效果
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        if (scrollView.contentOffset.y > 0) {   // 上滑
            if(self.bgScrollView.contentOffset.y < 0) {
                [UIView animateWithDuration:.3
                                      delay:0
                                    options:UIViewAnimationOptionCurveEaseInOut
                                 animations:^{
                                     [self.bgScrollView setContentOffset:CGPointZero animated:NO];
                                 } completion:nil];
            }
        } else {    // 下滑
            if (self.bgScrollView.contentOffset.y > -64) {
                [UIView animateWithDuration:.3
                                      delay:0
                                    options:UIViewAnimationOptionCurveEaseInOut
                                 animations:^{
                                     [self.bgScrollView setContentOffset:CGPointMake(0, -64) animated:NO];
                                 } completion:nil];
            }
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (section == 0) ? 1 : self.searchPoiArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kReuseCellId];
    }
    if (indexPath.section == 0) {
        cell.textLabel.text = @"[位置]";
        cell.detailTextLabel.text = self.currentAddress;
    } else {
        if (indexPath.row < self.searchPoiArray.count) {
            AMapPOI *poi = self.searchPoiArray[indexPath.row];
            cell.textLabel.text = poi.name;
            cell.detailTextLabel.text = poi.address;
        }
    }
    if (self.selIndexPath && indexPath.section == self.selIndexPath.section && indexPath.row == self.selIndexPath.row) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    self.selIndexPath = indexPath;
    [self.tableView reloadData];
    if (indexPath.section == 0) {
        [self didPositionCellTapped];
        return;
    }
    
    if (indexPath.row < self.searchPoiArray.count) {
        AMapPOI *selectedPoi = self.searchPoiArray[indexPath.row];
        [self didSelectTableViewWithMapPoi:selectedPoi];
    }
}
//- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
//    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    cell.accessoryType = UITableViewCellAccessoryNone;
//}
#pragma mark - MAMapViewDelegate
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    if (!updatingLocation) {
        return;
    }
    if (userLocation.location.horizontalAccuracy < 0) {
        return;
    }
    // only the first locate used.
    if (!self.isLocated) {
        self.isLocated = YES;
        self.mapView.userTrackingMode = MAUserTrackingModeFollow;
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude)];
        [self actionSearchAroundAt:userLocation.location.coordinate];
    }
}
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    NSLog(@"%s", __FUNCTION__);
    if (!self.isMapRegionChangedFromTb && mapView.userTrackingMode == MAUserTrackingModeNone) {
        [self actionSearchAroundAt:mapView.centerCoordinate];
    }
    
    self.isMapRegionChangedFromTb = NO;
}

#pragma mark - AMapSearchDelegate
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    if (!response.pois.count) {
        NSLog(@"没有更多数据了。。。");
        [self refreshWholeViewWithEnd:YES];
        return;
    }
    
    if (self.searchPage == 1) {
        self.selIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.searchPoiArray removeAllObjects];
    }
    [self.searchPoiArray addObjectsFromArray:response.pois];
//    self.selIndexPath = nil;
    [self refreshWholeViewWithEnd:NO];
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {
    if (response.regeocode != nil) {
        self.currentAddress = response.regeocode.formattedAddress;
        NSIndexPath *reloadIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[reloadIndexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = searchController.searchBar.text;
    NSLog(@"输入的搜索词语是%@", searchString);
    
    // hand over the filtered results to our search results table
    EFAPjtResultsTVC *tableController = (EFAPjtResultsTVC *)self.searchController.searchResultsController;
    tableController.keywords = searchString;
    [tableController refreshNewData];
}
#pragma mark - UISearchControllerDelegate
//- (void)didPresentSearchController:(UISearchController *)searchController {
//    self.bgScrollView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
//}
- (void)didDismissSearchController:(UISearchController *)searchController {
    self.searchController.searchBar.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44);
    self.bgScrollView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
}
#pragma mark - EFAPjtResultsTVCDelegate
- (void)resultsDidSelectPoint:(AMapPOI *)poi {
    // 搜索界面消失
    [self.searchController setActive:NO];
    
//    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude)];
    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
    [self.mapView setCenterCoordinate:coord animated:YES];
//    [self actionSearchAroundAt:coord];
}
#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sendBarBtnTapped:(UIBarButtonItem *)item {
    CLLocationCoordinate2D coord = self.mapView.userLocation.location.coordinate;   //!< 初始化为用户所在位置
    NSString *address = @"";    ///< 初始化为空
    if (self.selIndexPath.section == 0) {
        coord = self.mapView.centerCoordinate;
        address = self.currentAddress;
    } else {
        if (self.selIndexPath.row < self.searchPoiArray.count) {
            AMapPOI *poi = self.searchPoiArray[self.selIndexPath.row];
            coord = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
            address = [NSString stringWithFormat:@"%@", poi.address];
        }
    }
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.successHandle) {
            self.successHandle(coord, address);
            self.successHandle = nil;
        }
    }];
}
#pragma mark - private methods
- (void)actionSearchAroundAt:(CLLocationCoordinate2D)coordinate {
    self.searchPage = 1;
    
    [self searchReGeocodeWithCoordinate:coordinate];
    [self searchPoiWithCenterCoordinate:coordinate];
    
    // 执行一下动画效果
    [self centerAnnotationAnimimate];
}
// 根据中心点坐标来搜周边的POI
- (void)searchPoiWithCenterCoordinate:(CLLocationCoordinate2D)cord {
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    
    request.location = [AMapGeoPoint locationWithLatitude:cord.latitude longitude:cord.longitude];
    request.radius = 3000;
    request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施"; ///< 搜索的types
    request.sortrule = 0;
    request.page = self.searchPage; //!< 翻页使用的page
    
    NSLog(@"当前请求的Page = %ld", (long)self.searchPage);
    
    [self.search AMapPOIAroundSearch:request];
}
- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate {
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    
    regeo.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeo.requireExtension = YES;
    
    [self.search AMapReGoecodeSearch:regeo];
}
- (void)didSelectTableViewWithMapPoi:(AMapPOI *)selectedPoi {
    // 防止连续点击多次
    if (self.isMapRegionChangedFromTb) {
        return;
    }
    
    self.isMapRegionChangedFromTb = YES;
    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(selectedPoi.location.latitude, selectedPoi.location.longitude);
    [self.mapView setCenterCoordinate:coord animated:YES];
}
- (void)didPositionCellTapped {
    // 防止连续点击多次
    if (self.isMapRegionChangedFromTb) {
        return;
    }
    
    self.isMapRegionChangedFromTb = YES;
    [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
}
- (void)refreshWholeViewWithEnd:(BOOL)end {
    // 尾部加载更多的显示
    if (end) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    [self.tableView reloadData];
}
- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}
- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
//    [self requestPjtDeviceListWithHeader:isHeader];
    if (!isHeader) {
        self.searchPage++;
        [self searchPoiWithCenterCoordinate:self.mapView.centerCoordinate];
    }
}
/* 移动窗口弹一下的动画 */
- (void)centerAnnotationAnimimate {
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         CGPoint center = self.centerImgView.center;
                         center.y -= 20;
                         [self.centerImgView setCenter:center];}
                     completion:nil];
    
    [UIView animateWithDuration:0.45
                          delay:0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         CGPoint center = self.centerImgView.center;
                         center.y += 20;
                         [self.centerImgView setCenter:center];}
                     completion:nil];
}
#pragma mark - network request
#pragma mark - getters and setters
- (UIBarButtonItem *)cancelBarBtnItem {
    if (!_cancelBarBtnItem) {
        _cancelBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
    }
    return _cancelBarBtnItem;
}
- (UIBarButtonItem *)sendBarBtnItem {
    if (!_sendBarBtnItem) {
        _sendBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_sendBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_sendBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _sendBarBtnItem;
}

- (AMapSearchAPI *)search {
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}

- (NSMutableArray<AMapPOI *> *)searchPoiArray {
    if (!_searchPoiArray) {
        _searchPoiArray = [NSMutableArray array];
    }
    return _searchPoiArray;
}
- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

- (UISearchController *)searchController {
    if (!_searchController) {
        EFAPjtResultsTVC *tvc = [[EFAPjtResultsTVC alloc] init];
        tvc.delegate = self;
        _searchController = [[UISearchController alloc] initWithSearchResultsController:tvc];
        _searchController.searchResultsUpdater = self; ///< 设置UISearchControllerDelegate协议代理
        _searchController.dimsBackgroundDuringPresentation = YES;///<是否添加半透明覆盖层
        _searchController.hidesNavigationBarDuringPresentation = YES;///< 是否隐藏导航栏
        _searchController.delegate = self;
        _searchController.searchBar.delegate = self;
        _searchController.searchBar.placeholder = @"搜索地点";
        //设置背景图是为了去掉上下黑线
        UIImage* searchBarBg = [UIImage xd_getImageWithColor:[UIColor whiteColor] andHeight:1.0f];
        [_searchController.searchBar setBackgroundImage:searchBarBg forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
        //        _searchController.searchBar.tintColor = [UIColor whiteColor];
        _searchController.searchBar.barTintColor = [UIColor whiteColor];
        UITextField *searchField = [_searchController.searchBar valueForKey:@"searchField"];
        if (searchField) {
            [searchField setBackgroundColor:[UIColor xd_colorWithHex:0xEEEEEE]];
            searchField.layer.cornerRadius = 4.0f;
            searchField.layer.masksToBounds = YES;
        }
        [_searchController.searchBar sizeToFit];
        _searchController.searchBar.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44);
    }
    return _searchController;
}

@end
